#include "stdafx.h"
#include "SpecialCardPiecesDrop.h"
#include "InstanceTouch.h"
#include <sstream>
#include "time.h"
#include <algorithm>

DECL_INSTANCE_TOUCH(ETouch_SpecialCardPiecesConfig);

struct  SpecialCardPiecesConfigReflectionRegister
{
	SpecialCardPiecesConfigReflectionRegister()
	{

		REGISTER_REFLECTION_MEMBER(SpecialCardPiecesConfig,m_iID,INVALID_ID).Editor_SetAsPrimaryKey();
		REGISTER_REFLECTION_MEMBER(SpecialCardPiecesConfig,m_sDisplayName,std::string("DefaultName")).Editor_SetAsDisplayName();
		REGISTER_REFLECTION_MEMBER(SpecialCardPiecesConfig,m_iCardPiecesDef,INVALID_ID).Editor_SetAsForeignKey(eDefGroup_Default,eDefaultDef_Card);		
		REGISTER_REFLECTION_MEMBER(SpecialCardPiecesConfig,m_iExchangeNeedNum,2).Editor_SetAsRaw();		
		REGISTER_REFLECTION_MEMBER(SpecialCardPiecesConfig,m_sFromDate,std::string("2013-01-01")).Editor_SetAsDateTime("Time");
		REGISTER_REFLECTION_MEMBER(SpecialCardPiecesConfig,m_sToDate,std::string("2013-01-02")).Editor_SetAsDateTime("Time");

		GlobalClassManager::Instance().RegisterClass(SpecialCardPiecesConfig::s_GetReflection(),eDefaultDef_SpecialCardPiecesConfig);
		GlobalDefManager::Instance().RegisterDefManger(&SpecialPiecesConfigManager::Instance());

	}
}__specialcardpiecesconfigreflectionregister;

rewrite  void SpecialCardPiecesConfig::OnArchieveReaded()
{
	{
		std::stringstream ss;
		ss<<m_sFromDate<<" 00:00:00";
		m_iFromDateTime=Util::PraseISOTimeString(ss.str().c_str());
	}
	{
		std::stringstream ss;
		ss<<m_sToDate<<" 00:00:00";
		m_iToDateTime=Util::PraseISOTimeString(ss.str().c_str());
	}

}

bool SpecialCardPiecesConfig::IsInTime() const
{
	time_t iNow =::time(NULL);
	return m_iFromDateTime<=iNow && m_iToDateTime>iNow;
}
static bool __CompareByToDateTime(const SpecialCardPiecesConfig* pA,const SpecialCardPiecesConfig* pB)
{
	return pA->m_iToDateTime<pB->m_iToDateTime;
}

const SpecialCardPiecesConfig * SpecialPiecesConfigManager::GetRecentSpecialCardPiecesConfig()
{
	time_t iNow =::time(NULL);
	if(NULL!=m_pSpecialCardPiecesDrop && 
		(m_pSpecialCardPiecesDrop->m_iToDateTime>iNow ))
	{
		return m_pSpecialCardPiecesDrop;
	}
	else
	{
		m_pSpecialCardPiecesDrop=NULL;
		std::vector<const SpecialCardPiecesConfig *> vDefs;
		Enumerate(vDefs);
		std::sort(vDefs.begin(),vDefs.end(),__CompareByToDateTime);
		for(uint32 ii=0;ii<vDefs.size();ii++)
		{
			const SpecialCardPiecesConfig * pDef=vDefs[ii];
			if(pDef->m_iToDateTime>iNow)
			{
				m_pSpecialCardPiecesDrop=pDef;
				break;
			}
		}
		return m_pSpecialCardPiecesDrop;
	}
}